<?php namespace App\Admin\Access\Role\Listeners;

use Auth;
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Service\Listeners\CreateListener as Base;

class CreateListener extends Base {
    
    public function onCreateGeneratedData(){
        $user = Auth::user();
        $repository = $this->service->repository;
        $data = $this->service->createData;
        $data['parent_id'] = !$data['parent_id'] ? ($user->isAdmin() ? '0' : $user->role->role_id) :  $data['parent_id'];
        $data['role_id'] = $repository->getNextId($data['parent_id']);
        $this->service->createData = $data;
    }
    
    public function onCreateSaved(){
        $model = $this->service->createModel;
        if($model->parent_id > '0'){
            $parentModel = $this->service->repository->resetQuery()->resetCriteria(true)->addCriteria(new FixedCriteria('role_id', $model->parent_id))->first();
            if($parentModel){
                $newCount = intval($parentModel->sub_count) + 1;
                $this->service->repository->resetQuery()->resetCriteria(true)->addCriteria(new FixedCriteria('role_id', $parentModel->role_id))->update(['sub_count' => $newCount]);
            }
        }
    }
}